package cn.edu.gzhu.workOrderManagement.intercepter;

import cn.edu.gzhu.workOrderManagement.constants.MessageConstant;
import cn.edu.gzhu.workOrderManagement.constants.WorkOrderFollowStatus;
import cn.edu.gzhu.workOrderManagement.enumeration.UserAuthorityEnum;
import cn.edu.gzhu.workOrderManagement.mapper.WorkOrderMapper;
import cn.edu.gzhu.workOrderManagement.pojo.entity.WorkOrder;
import cn.edu.gzhu.workOrderManagement.util.ResponseUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;
//只有总部商务可以删除待跟进的工单
@Component
@Slf4j
public class WorkOrderDeleteInterceptor implements HandlerInterceptor {

    @Autowired
    WorkOrderMapper workOrderMapper;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Claims claims =(Claims) request.getAttribute("claims");
        UserAuthorityEnum authority = UserAuthorityEnum.value2Object(claims.get("authority").toString());

        if (!UserAuthorityEnum.HEAD_BUSINESS.equals(authority)&&!UserAuthorityEnum.CLIENT.equals(authority)) {
            ResponseUtil.failResponse(response,MessageConstant.PERMISSION_DENIED);

            return false;
        }

        String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        JSONArray jsonArray = JSONUtil.parseArray(body);
        List<String> uuids = JSONUtil.toList(jsonArray, String.class);

        List<WorkOrder> workOrders = workOrderMapper.selectList(new LambdaUpdateWrapper<WorkOrder>().in(WorkOrder::getUuid, uuids));
        for (WorkOrder workOrder : workOrders) {
            if (authority.equals(UserAuthorityEnum.CLIENT)) {
                if (!workOrder.getRequestUser().equals(claims.get("username"))) {

                    ResponseUtil.failResponse(response,MessageConstant.PERMISSION_DENIED);
                    return false;
                }
            }

        }
        return true;
    }
}
